package cn.bearspark.article.provider.dao.buffer;

import cn.bearspark.article.provider.dao.key.CategoryBufferKeyBuilder;
import cn.bearspark.article.provider.dao.mapper.CategoryMapper;
import cn.bearspark.framework.redis.starter.buffer.list.RedisBaseListBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 专栏分类 id 的 list 数据结构的缓存器
 *
 * @author f
 */
@Component
public class CategoryIdListBuffer extends RedisBaseListBuffer<Long> {

    /**
     * 每个用户的专栏分类的数量必定少于 100
     */
    private static final int CATEGORY_MAX_SIZE = 100;

    private final CategoryMapper categoryMapper;

    private final CategoryBufferKeyBuilder categoryBufferKeyBuilder;

    public CategoryIdListBuffer(RedisTemplate<String, Object> redisTemplate,
                                CategoryMapper categoryMapper,
                                CategoryBufferKeyBuilder categoryBufferKeyBuilder) {
        super(redisTemplate);

        this.categoryMapper = categoryMapper;
        this.categoryBufferKeyBuilder = categoryBufferKeyBuilder;
    }

    /**
     * 获取指定用户创建的所有专栏分类 id
     *
     * @param listedUserId 待获取专栏分类简要信息集合的用户 id
     * @return 指定用户创建的所有专栏分类 id 集合
     */
    public List<Long> listCategoryId(long listedUserId) {
        return super.range(
                categoryBufferKeyBuilder.buildIdListKey(listedUserId), 0, CATEGORY_MAX_SIZE,
                () -> categoryMapper.listCategoryId(listedUserId)
        );
    }

    /**
     * 判断指定用户创建的专栏分类数量是否超出限制
     *
     * @param userId 指定的用户 id
     * @return 指定用户创建的专栏分类数量是否超出限制
     */
    public boolean isExceedRange(long userId) {
        String idListKey = categoryBufferKeyBuilder.buildIdListKey(userId);
        Long categoryNum = redisTemplate.opsForList().size(idListKey);
        if (categoryNum == null) {
            categoryNum = categoryMapper.countCategoryNum(userId);
        }
        return categoryNum >= CATEGORY_MAX_SIZE;
    }

    /**
     * 清理指定用户创建的所有专栏分类 id 集合的缓存
     *
     * @param userId 指定的用户 id
     */
    public void clean(long userId) {
        super.clean(categoryBufferKeyBuilder.buildIdListKey(userId));
    }
}
